#pragma once
#include "cgzITask.h"
class cgzCThread
{
public:
    friend class cgzCThreadPool;
    cgzCThread(cgzCThreadPool *pThreadPool);
    ~cgzCThread();

public:
    void start();
    void stop();
    void run();

public:
    void wakeUp();

public:
    bool setbusy(cgzITask *pTask);
    bool setIdle();
    bool hasIdle();

private:
    std::thread *m_thread;
    std::mutex mtx_run;
    std::shared_mutex mtx_opt;
    std::condition_variable cv;
    bool m_bRunning;

private:
    cgzCThreadPool *m_pThreadPool;

private:
    cgzITask *m_pTask = nullptr;
};

class cgzCThreadPool
{
private:
    cgzCThreadPool(int nThreadNum);
    ~cgzCThreadPool();

public:
    void start();
    void shutdown();
    void stop();
    void run();
    void exec();
    void waits();

public:
    void addTask(const char *origin, cgzITask *pTask);
    void addTask(const char *origin, const char *target, cgzIData *pTask);
    void addTask(const int origin, const int target, cgzIData *pTask);

public:
    void setLog(int logtid, int logfid, int loglvl);
    void errLog(const char *file, const char *func, const int line, const char *msg);

public:
    void wakeUp();
    void wakeDown();

public:
    bool isrunning();

public:
    const char *getname(int origin);

public:
    const cgzITask *getTask(int id);

public:
    int getidbyname(const char *name);
    void push_thread(std::thread* pth);
    
public:
    static cgzCThreadPool *Instance(int nThreadNum = 0);

private:
    int m_nThreadNum;
    cgzCThread **m_pThreadList;
    std::thread *m_thread;
    std::list<std::thread*> m_threadAll;

private:
    std::map<int, cgzITask *> m_taskMap;          //{[id] = 任务}
    std::map<std::string, cgzITask *> m_taskNMap; //{[name]=任务}
    std::map<int, std::string> m_taskINMap;       //{[id]=name}
    std::mutex mtx_run;
    std::shared_mutex mtx_opt;
    std::shared_mutex mtx_que;
    std::condition_variable cv;

private:
    std::map<int, cgzITask *> m_taskIdleMap; // 空闲的服务队列
    std::list<cgzITask *> m_taskBusyQueue;   // 工作的服务队列
    std::list<cgzITask *> m_taskIdleQueue;   // 空闲的服务队列
    std::list<cgzITask *> m_taskTempQueue; // 临时的服务队列
    std::list<cgzIData *> m_taskDataQueue; // 新增的执行任务

public:
    // 日志相关
    std::atomic<int> m_logtid = {-1};
    std::atomic<int> m_logfid = {-1};
    std::atomic<int> m_loglvl = {-1};

private:
    static cgzCThreadPool *m_pInstance;
    std::atomic<bool> m_bRunning = {true};
    std::atomic<bool> m_bShutdown = {false};
    std::atomic<bool> m_bwake = {true};
};